from tkinter.ttk import Treeview

from django.db.models import Q
from django.shortcuts import render
from django.views.generic import ListView
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from unicodedata import category

from course.models import CourseModel01
from course.ser import CourseSer
from home.models import CategoryModel
from home.ser import CategorySer, Category


# Create your views here.
class DirectionView(APIView):
    def get(self,request):
        direction = CategoryModel.objects.filter(is_del=False,parent=None).order_by('order')
        ser = Category(instance=direction,many=True)
        return Response({"msg":"ok","code":200,"data":ser.data})


class CategoryView(APIView):
    def get(self,request):
        id = request.GET.get('pk')
        if int(id) !=0:
            category = CategoryModel.objects.filter(is_del=False,parent=id).order_by('order')
        else:
            category = CategoryModel.objects.filter(Q(is_del=False),~Q(parent=None)).order_by('order')
        ser = Category(instance=category,many=True)
        return Response({"msg":"ok","code":200,"data":ser.data})

class CoursePage(PageNumberPagination):
    page_size = 2
    page_query_param = 'page'
    page_size_query_param = 'size'

class CourseView(ListAPIView):
    queryset = CourseModel01.objects.all()
    serializer_class = CourseSer
    pagination_class = CoursePage
    def get_queryset(self):
        query = Q()
        cateid = int(self.request.GET.get("cate"))
        direction = int(self.request.GET.get("direction"))
        level = self.request.GET.get('level',"")
        ordering = self.request.GET.get('ordering',"")
        if cateid != 0:
            query&=Q(category=cateid)
        if direction !=0 and cateid == 0 :
            data = CategoryModel.objects.filter(is_del=False,parent=direction)
            cateList = []
            for i in data:
                cateList.append(i.id)
            query&=Q(category__in=cateList)
        if level:
            query&=Q(level=level)
        if ordering:
            return self.queryset.filter(query).order_by(ordering)
        return self.queryset.filter(query)
class DetailesView(APIView):
    def get(self,request):
        course = CourseModel01.objects.filter(is_del=False,id=request.query_params.get('id')).first()
        ser = CourseSer(instance=course)
        return Response({"msg":"ok","code":200,"data":ser.data})